//
//  UILabel+Utils.m
//  WXReader
//
//  Created by LL on 2021/9/10.
//  Copyright © 2021 Andrew. All rights reserved.
//

#import "UILabel+Utils.h"

@implementation UILabel (Utils)

- (CGFloat)w_textWidth {
    if (self.attributedText) {
        return [TL_ViewHelper calcTextSize:CGSizeMake(CGFLOAT_MAX, 30.0)
                                 text:self.attributedText
                        numberOfLines:1
                                 font:nil
                        textAlignment:self.attributedText.alignment
                        lineBreakMode:self.attributedText.lineBreakMode
                   minimumScaleFactor:0
                         shadowOffset:CGSizeZero].width;
    }
    
    return [TL_ViewHelper calcTextSize:CGSizeMake(CGFLOAT_MAX, 30.0)
                             text:self.text
                    numberOfLines:1
                             font:self.font
                    textAlignment:self.textAlignment
                    lineBreakMode:self.lineBreakMode
               minimumScaleFactor:0
                     shadowOffset:CGSizeZero].width;
}

- (CGFloat)w_textHeight {
    if (self.attributedText) {
        return [TL_ViewHelper calcTextSize:CGSizeMake(self.preferredMaxLayoutWidth, CGFLOAT_MAX)
                                 text:self.attributedText
                        numberOfLines:self.numberOfLines
                                 font:nil
                        textAlignment:self.attributedText.alignment
                        lineBreakMode:self.attributedText.lineBreakMode
                   minimumScaleFactor:0
                         shadowOffset:CGSizeZero].height;
    }
    
    return [TL_ViewHelper calcTextSize:CGSizeMake(self.preferredMaxLayoutWidth, CGFLOAT_MAX)
                             text:self.text
                    numberOfLines:self.numberOfLines
                             font:self.font
                    textAlignment:self.textAlignment
                    lineBreakMode:self.lineBreakMode
               minimumScaleFactor:0
                     shadowOffset:CGSizeZero].height;
}
- (void)attributedStringWithHTMLText:(NSString *)text
                            fontSize:(CGFloat)fontSize
                    characterSpacing:(CGFloat)characterSpacing
                        lineSpacing:(CGFloat)lineSpacing
                   paragraphSpacing:(CGFloat)paragraphSpacing
                          alignment:(NSTextAlignment)alignment {
    
    // 检查文本是否为空或nil
    if (!text || text.length == 0) {
        self.text = @"";
        return;
    }
    
    // 将换行符替换为HTML换行标签
    text = [text stringByReplacingOccurrencesOfString:@"\n" withString:@"<br>"];
    
    // 创建HTML数据
    NSData *htmlData = [text dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *options = @{
        NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
        NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding)
    };
    
    NSError *error = nil;
    NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithData:htmlData
                                                                                       options:options
                                                                            documentAttributes:nil
                                                                                         error:&error];
    
    if (error) {
        NSLog(@"富文本解析失败: %@", error.localizedDescription);
        // 解析失败时使用普通文本创建属性字符串
        attributedText = [[NSMutableAttributedString alloc] initWithString:text];
    }
    
    // 安全地获取文本范围
    NSRange fullRange = NSMakeRange(0, attributedText.length);
    if (fullRange.length == 0) {
        self.text = @"";
        return;
    }
    
    // 设置字体 - 添加安全检查
    UIFont *font = [UIFont fontWithName:@"SourceSerif4-Regular" size:fontSize];
    
    // 如果自定义字体不可用，使用系统字体作为后备
    if (!font) {
        NSLog(@"自定义字体 'SourceSerif4-Regular' 不可用，使用系统字体代替");
        font = [UIFont systemFontOfSize:fontSize];
    }
    
    // 安全地添加字体属性
    if (font) {
        [attributedText addAttribute:NSFontAttributeName
                              value:font
                              range:fullRange];
    }
    
    // 安全地添加字间距属性
    [attributedText addAttribute:NSKernAttributeName
                          value:@(characterSpacing)
                          range:fullRange];
    
    // 创建段落样式 - 取消首行缩进
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineSpacing = lineSpacing;
    paragraphStyle.paragraphSpacing = paragraphSpacing;
    paragraphStyle.firstLineHeadIndent = 0; // 取消首行缩进
    paragraphStyle.headIndent = 0; // 取消所有行的缩进
    paragraphStyle.alignment = alignment;
    
    // 安全地添加段落样式属性
    [attributedText addAttribute:NSParagraphStyleAttributeName
                          value:paragraphStyle
                          range:fullRange];
    
    // 处理多段落的首行空格问题
    [self removeLeadingSpacesFromAllParagraphs:attributedText];
    
    self.attributedText = attributedText;
}

// 辅助方法：移除属性字符串中所有段落的首行空格
- (void)removeLeadingSpacesFromAllParagraphs:(NSMutableAttributedString *)attributedString {
    if (attributedString.length == 0) return;
    
    NSString *string = attributedString.string;
    
    // 按段落分割字符串
    NSArray *paragraphs = [string componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
    
    // 记录每个段落的起始位置
    NSMutableArray *paragraphRanges = [NSMutableArray array];
    NSUInteger currentLocation = 0;
    
    for (NSString *paragraph in paragraphs) {
        NSRange paragraphRange = NSMakeRange(currentLocation, paragraph.length);
        [paragraphRanges addObject:[NSValue valueWithRange:paragraphRange]];
        currentLocation += paragraph.length;
        
        // 加上换行符的长度（除了最后一个段落）
        if (currentLocation < string.length) {
            currentLocation += 1; // 换行符长度
        }
    }
    
    // 从后往前处理段落，这样删除字符不会影响前面段落的位置
    for (NSValue *rangeValue in [paragraphRanges reverseObjectEnumerator]) {
        NSRange paragraphRange = [rangeValue rangeValue];
        
        // 如果段落为空，跳过
        if (paragraphRange.length == 0) continue;
        
        // 查找段落中第一个非空格字符的位置
        NSCharacterSet *whitespaceSet = [NSCharacterSet whitespaceCharacterSet];
        NSUInteger firstNonSpaceIndexInParagraph = paragraphRange.location;
        BOOL foundNonSpace = NO;
        
        for (NSUInteger i = paragraphRange.location; i < paragraphRange.location + paragraphRange.length; i++) {
            unichar character = [string characterAtIndex:i];
            if (![whitespaceSet characterIsMember:character]) {
                firstNonSpaceIndexInParagraph = i;
                foundNonSpace = YES;
                break;
            }
        }
        
        // 如果整个段落都是空格，保留一个空格（避免完全删除段落）
        if (!foundNonSpace && paragraphRange.length > 0) {
            firstNonSpaceIndexInParagraph = paragraphRange.location + paragraphRange.length;
        }
        
        // 计算需要删除的空格数量
        NSUInteger spacesToDelete = firstNonSpaceIndexInParagraph - paragraphRange.location;
        
        // 如果段落开头有空格，则删除它们
        if (spacesToDelete > 0) {
            NSRange deleteRange = NSMakeRange(paragraphRange.location, spacesToDelete);
            [attributedString deleteCharactersInRange:deleteRange];
        }
    }
}


- (void)attributedStringWithHTMLText:(NSString *)text
                            fontSize:(CGFloat)fontSize
                    characterSpacing:(CGFloat)characterSpacing
                        lineSpacing:(CGFloat)lineSpacing
                   paragraphSpacing:(CGFloat)paragraphSpacing
                          alignment:(NSTextAlignment)alignment
                ifExceedWidthThen:(void (^)(CGFloat requiredHeight))exceedBlock {
    
    // 检查文本是否为空或nil
    if (!text || text.length == 0) {
        self.text = @"";
        if (exceedBlock) {
            exceedBlock(0);
        }
        return;
    }
    
    // 将换行符替换为HTML换行标签
    text = [text stringByReplacingOccurrencesOfString:@"\n" withString:@"<br>"];
    
    // 创建HTML数据
    NSData *htmlData = [text dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *options = @{
        NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
        NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding)
    };
    
    NSError *error = nil;
    NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithData:htmlData
                                                                                       options:options
                                                                            documentAttributes:nil
                                                                                         error:&error];
    
    if (error) {
        NSLog(@"富文本解析失败: %@", error.localizedDescription);
        // 解析失败时使用普通文本创建属性字符串
        attributedText = [[NSMutableAttributedString alloc] initWithString:text];
    }
    
    // 安全地获取文本范围
    NSRange fullRange = NSMakeRange(0, attributedText.length);
    if (fullRange.length == 0) {
        self.text = @"";
        if (exceedBlock) {
            exceedBlock(0);
        }
        return;
    }
    
    // 设置字体 - 添加安全检查
    UIFont *font = [UIFont fontWithName:@"SourceSerif4-Regular" size:fontSize];
    
    // 如果自定义字体不可用，使用系统字体作为后备
    if (!font) {
        NSLog(@"自定义字体 'SourceSerif4-Regular' 不可用，使用系统字体代替");
        font = [UIFont systemFontOfSize:fontSize];
    }
    
    // 安全地添加字体属性
    if (font) {
        [attributedText addAttribute:NSFontAttributeName
                              value:font
                              range:fullRange];
    }
    
    // 安全地添加字间距属性
    [attributedText addAttribute:NSKernAttributeName
                          value:@(characterSpacing)
                          range:fullRange];
    
    // 创建并设置段落样式
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineSpacing = lineSpacing;
    paragraphStyle.paragraphSpacing = paragraphSpacing;
    paragraphStyle.alignment = alignment;
    
    // 安全地添加段落样式属性
    [attributedText addAttribute:NSParagraphStyleAttributeName
                          value:paragraphStyle
                          range:fullRange];
    
    self.attributedText = attributedText;
    
    // 检查内容宽度是否超过UILabel宽度，并返回所需高度
    [self checkIfContentExceedsWidthWithExceedBlock:exceedBlock];
}

// 辅助方法：检查内容是否超过UILabel宽度，并返回所需高度
- (void)checkIfContentExceedsWidthWithExceedBlock:(void (^)(CGFloat requiredHeight))exceedBlock {
    if (!exceedBlock) return;
    
    // 确保UILabel已经有布局
    if (self.bounds.size.width <= 0) {
        // 如果还没有布局，延迟检查
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self checkIfContentExceedsWidthWithExceedBlock:exceedBlock];
        });
        return;
    }
    
    // 计算属性文本所需的大小
    CGSize maxSize = CGSizeMake(self.bounds.size.width, CGFLOAT_MAX);
    CGRect textRect = [self.attributedText boundingRectWithSize:maxSize
                                                       options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
                                                       context:nil];
    
    // 检查内容宽度是否超过UILabel宽度
    BOOL exceedsWidth = textRect.size.width > self.bounds.size.width;
    
    // 获取完整显示所需的高度（向上取整）
    CGFloat requiredHeight = ceil(textRect.size.height);
    
    if (exceedsWidth) {
        // 执行block并返回所需高度
        exceedBlock(requiredHeight);
    } else {
        // 即使没有超过宽度，也返回所需高度，方便调用者使用
        exceedBlock(requiredHeight);
    }
}
@end
